# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午2:44
# @Author  : xiaowanzi
# @File    : grid_manager.py
import jsonpath
from requests import session, get
from base.log import logger


def delete_session(node_url, session_id):
    s = session()
    headers = {"X-REGISTRATION-SECRET": ""}
    resp = s.delete(f"{node_url}/session/{session_id}")
    if resp.status_code == 200:
        logger.info(f"删除NODE({node_url})的SESSIoN({session_id})成功")
    else:
        logger.info(f"删除{node_url}的{session_id}失败")


def get_all_running_session(url):
    r_sessions = []
    status = get(f"{url}/status").json()
    sessions = jsonpath.jsonpath(status, "$..[?(session=='')]")
    for session in sessions:
        if session:
            session_id = session['sessionId']
            node_url = session['uri']
            r_sessions.append({"session id": session_id, "node url": node_url})
    return r_sessions


def get_session_node(url, session_id):
    r_sessions = get_all_running_session(url)
    for s in r_sessions:
        if s and s['session id'] == session_id:
            node_url = s['node url']
            logger.info(f"获取node成功，node地址为{node_url}")
    return node_url


def delete_all_sessions(url):
    r_session = get_all_running_session(url)
    for session in r_session:
        delete_session(session['node_url'], session['session_id'])
    logger.info(f"成功删除全部{url}里的grid_session")


if __name__ == '__main__':
    delete_session('http://192.168.69.167:4444', '4a1b692f7446d092c48520c73932a392')
    get_all_running_session('http://192.168.69.167:4444')